package compress

import (
	"archive/tar"
	"changeme/backend/utils"
	"compress/gzip"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
)

func GZip(path string, createPath string) (err error) {
	if _, exist := utils.Exist(path); !exist {
		return fs.ErrNotExist
	}

	gzipFile, err := os.OpenFile(createPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0755)
	defer func() {
		_ = gzipFile.Close()
	}()
	if err != nil {
		return err
	}

	gzipWriter := gzip.NewWriter(gzipFile)
	defer func() {
		_ = gzipWriter.Close()
	}()
	return gzipCompress(path, gzipWriter)
}

func gzipCompress(path string, w *gzip.Writer) (err error) {
	if _, exist := utils.Exist(path); !exist {
		return fs.ErrNotExist
	}

	tarWriter := tar.NewWriter(w)
	defer func() {
		_ = tarWriter.Close()
	}()

	return TarCompress("", path, tarWriter)
}

func UnGZip(absFilePath string, extractPath string) (err error) {
	if !utils.ExistFile(absFilePath) {
		return fs.ErrNotExist
	}

	gzipFile, err := os.Open(absFilePath)
	defer func() {
		_ = gzipFile.Close()
	}()
	if err != nil {
		return err
	}

	gzipReader, err := gzip.NewReader(gzipFile)
	defer func() {
		_ = gzipReader.Close()
	}()
	if err != nil {
		return err
	}

	abs, _ := filepath.Abs(extractPath)
	tarFileName := strings.TrimSuffix(filepath.Base(absFilePath), ".gz")
	if !utils.EndWith(tarFileName, ".tar") {
		tarFileName += ".tar"
	}
	tarFilePath := filepath.Join(abs, tarFileName)
	tarFile, err := os.OpenFile(tarFilePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0755)
	defer func() {
		_ = tarFile.Close()
	}()

	if err != nil {
		return err
	}

	fmt.Printf("解压 %s \n\t=> %s\n", absFilePath, tarFilePath)
	_, err = io.Copy(tarFile, gzipReader)
	if err != nil {
		return err
	}

	return
}
